<script setup lang="ts">
import {useRoute} from "vue-router";
import {onMounted, reactive, ref, UnwrapRef} from "vue";


import {useMaterialInStore} from "@/stores/materialInStore.js";

import {useMaterialTypeStore} from "@/stores/materialTypeStore.ts";
import {useDataPublicStore} from "@/stores/dataPublicStore.ts";
import {ComponentSize, ElMessage, FormInstance, FormProps, FormRules} from "element-plus";
import ContextMenu from "@imengyu/vue3-context-menu";
import router from "@/router/index.ts";
import CameraCapture from "@/views/PublicCom/cameraCapture.vue";
import FileUpload from "@/views/PublicCom/ImageFilesUpload.vue";
import {getProjectListAPI} from "@/apis/projectInfo.js";
import {useGetOneByIdAPI, useModifyOneAPI} from "@/apis/materialIn.js";

const materialInStore=useMaterialInStore();


const route=useRoute();


// 获取材料类型
const materialTypeStore=useMaterialTypeStore();
materialTypeStore.getFullMaterialType(1,10000);

// 获取pinia数据
const dataStore=useDataPublicStore();

// submit按钮的状态
const disableSwitch=ref(false);

// 显示在页面上的图像地址数组
const photoList=ref([]);
// y用于比较被删除图像的数组
const tempPhotoList=ref([]);
// 用于往后端传送需要删除的图像的地址数组
const checkList=ref([]);

if (materialInStore.materialInStore.materialInPhotoList!==undefined){
  materialInStore.materialInStore.materialInPhotoList.forEach((item:string)=>{
    photoList.value.push(item.photoUrl);
    tempPhotoList.value.push(item.photoUrl);
  })

}

const size=ref<ComponentSize>('default')
const labelPosition = ref<FormProps['labelPosition']>('right');
const formData=new FormData();

interface ruleForm{
  id:string,
  materialId:string,
  materialName:string,
  brand:string,
  encode:string,
  description:string,
  location:string,
  model:string,
  number:number,
  pieces:string,
  typeName:string,
  originNumber:number,
  receiveProject:string,
  price:number,
  totalPrice:number,
}

let form=reactive<ruleForm>({
  id:'',
  materialId:'',
  materialName:'',
  brand:'',
  encode:'',
  description:'',
  location:'',
  model:'',
  number:0,
  pieces:'',
  typeName:'string',
  originNumber:0,
  receiveProject:'',
  price:0,
  totalPrice:0,
})
// 用于材料类型转换
const newMaterialTypeName=ref('')
const getMaterialTypeName=(typeNameInDb:UnwrapRef<string>)=>{
  newMaterialTypeName.value=typeNameInDb[0]+':'+typeNameInDb[1];
  form.typeName=newMaterialTypeName.value;
}

const receiveFromProjectList=ref([]);
const receiveFromProjectName=ref('')


const price=ref(0);
const totalPrice=ref(0);

const getTotalPrice=()=>{
  totalPrice.value=Math.round(price.value*form.number*100)/100;
}
const materialInNumberChange=()=>{
  totalPrice.value=Math.round(price.value*form.number*100)/100;
}




const materialInInfo=ref({});
onMounted( async ()=>{
  await getProjectListAPI(1,100000).then(res=>{
    receiveFromProjectList.value=res.data;
  })


  // await materialInStore.getOneByIdStore(route.params.id);

  const materialInRes=await useGetOneByIdAPI(route.params.id);

  materialInInfo.value=materialInRes.data;




  form.id=String(materialInInfo.value.id);
  form.materialName=materialInInfo.value.materialName;
  form.brand=materialInInfo.value.brand;
  form.encode=materialInInfo.value.encode;
  form.description=materialInInfo.value.description;
  form.location=materialInInfo.value.warehouse;
  form.model=materialInInfo.value.model;
  form.pieces=materialInInfo.value.pieces;
  form.typeName=materialInInfo.value.typeName;
  form.materialId=materialInInfo.value.materialId;
  newMaterialTypeName.value=form.typeName;
  price.value=materialInInfo.value.price;
  totalPrice.value=materialInInfo.value.totalPrice;
  form.originNumber=materialInInfo.value.number;
  form.number=materialInInfo.value.number;
  receiveFromProjectName.value=materialInInfo.value.receiveProject;



})

// 显示进度条配合函数
const format=(percentage:number)=>{
  return percentage===100?'100%':`${percentage}`
}

// 专门修正element-ui中图片预览必须要从第一张开始的bug
function  getPreviewImgList (index:number) {
  let arr = [];
  for (let i = 0; i < photoList.value.length; i++) {
    arr.push(photoList.value[i + index]);
    if (i + index >= photoList.value.length - 1) { // 为了取后边小值（采用绝对值）
      index = 0 - (i + 1);
    }
  }
  return arr;
}

// 点击鼠标 右键删除图片
const onContextMenu=(e:MouseEvent,index:number)=>{
  ContextMenu.showContextMenu({
    x:e.x,
    y:e.y,
    items:[
      {
        label:'删除',
        // 这里有三个数组，页面一打开时，photoList和tempPhotoList中都包含了已经存在的图片地址
        // checkList数组是空白数组
        onClick() {
          // 右键删除时，photoList会把点选的元素删除
          photoList.value.splice(index,1);
          // 遍历tempPhotoList数组，如果发现当中一个元素不包含在photoList数组中，就把这个元素存放在checkList数组中
          // 这个就可以告诉后端，需要删除的是那个图片
          tempPhotoList.value.forEach((item)=>{
            if (!photoList.value.includes(item)){
              checkList.value.push(item);
            }
          })
        },
      }
    ]
  })
}

//  todo  这个修改数量、单价还是有问题 2025年7月24日晚上
const modifyOneSummit=(formEl:FormInstance|undefined)=>{
  if (!formEl) return;
  formData.append("id", form.id);
  formData.append("materialName", form.materialName);
  formData.append("typeName", form.typeName);
  formData.append("brand", form.brand);
  formData.append("pieces", form.pieces);
  formData.append("number", form.number);
  formData.append("originNumber", form.originNumber);
  formData.append("model", form.model);
  formData.append("description", form.description);
  formData.append("materialId",form.materialId);
  formData.append('photoList',checkList.value);
  formData.append("encode",materialInStore.materialInStore.encode);
  formData.append("receiveProject",receiveFromProjectName.value);
  formData.append('price',price.value);
  formData.append('totalPrice',totalPrice.value);

  if (dataStore.uploadFileList.length>0){
    dataStore.uploadFileList.forEach((item:File)=>{
      formData.append('photoFiles',item);
    });
  }
  if (dataStore.photoFileList.length>0){
    dataStore.photoFileList.forEach((item:File)=>{
      formData.append('photoFiles',item);
    })
  }
  formEl.validate(async  (valid,fields)=>{
    if (valid){
      disableSwitch.value=true;
      await useModifyOneAPI(formData).then(res=>{
        if(res.code===200){
          dataStore.setPhotoFiles([]);
          dataStore.setUploadFileList([]);
          dataStore.saveDataObject({});
          dataStore.setOnUploadProgress(0);
         router.push({path: `/home/material/materialInDetail/${form.id}`});
        }
        else {
          ElMessage({
            type: 'error',
            message:res.msg
          })
           router.push({ path: `/home/material/materialModify/${form.id}`});
        }
      })
    }

  })
}

// 表单校验
const ruleFormRef=ref<FormInstance>();

const rules=reactive<FormRules<typeof form>>({
  materialName:[
    {required:true,message:'选填项'},
    // { validator: (rule,value,callback)=>{
    //     // 使用正则表达式校验，正则表达式写在/ 正则表达式  /之间
    //     // 这里是：/      ^[A-Za-z0-9]([ A-Za-z0-9_-]*[A-Za-z0-9])?$     /
    //     if(!/^[\u4E00-\u9FA5A-Za-z0-9_]{2,32}$/.test(value)){
    //       callback(new Error("输入中文或者英文、数字或者下划线且字符数2~32"));
    //     }else{
    //       //校验通过
    //       callback();
    //     }
    //   },trigger:'blur'  }
  ],
  brand:[
    {required:true,message:'选填项'},
    // {validator:(rule, value, callback)=>{
    //     // 这里填写规则
    //     if (!/^[\u4E00-\u9FA5A-Za-z0-9_]{2,16}$/.test(value)){
    //       callback(new Error('输入中文或者英文、数字或者下划线且字符数2~16'))
    //     }else {
    //       callback();
    //     }
    //   } ,trigger:'blur'}
  ],
  model:[
    {required:true,message:'选填项'},
    // {validator:(rule, value, callback)=>{
    //     // 这里填写规则
    //     if (!/^[\u4E00-\u9FA5A-Za-z0-9_]{2,16}$/.test(value)){
    //       callback(new Error('输入中文或者英文、数字或者下划线且字符数2~16'))
    //     }else {
    //       callback();
    //     }
    //   } ,trigger:'blur'}
  ],
  typeName:[
    {required:true,message:'选填项'},
    // {validator:(rule, value, callback)=>{
    //     // 这里填写规则
    //     if (!/^[\u4E00-\u9FA5A-Za-z0-9_]{2,16}$/.test(value)){
    //       callback(new Error('输入中文或者英文、数字或者下划线且字符数2~16'))
    //     }else {
    //       callback();
    //     }
    //   } ,trigger:'blur'}
  ],
  pieces:[
    {required:true,message:'选填项'},
    // {validator:(rule, value, callback)=>{
    //     // 这里填写规则
    //     if (!/^[\u4E00-\u9FA5A-Za-z0-9_]{1,8}$/.test(value)){
    //       callback(new Error('输入中文或者英文、数字或者下划线且字符数1~8'))
    //     }else {
    //       callback();
    //     }
    //   } ,trigger:'blur'}
  ],
  description:[
    {message:'选填项'},
    {min:0,max:256,message:'描述总字符在0~256之间'}
  ],
})

const handleParentChange=()=>{
  console.log(receiveFromProjectName.value);
}



</script>

<template>

  <!--  进度条-->
  <el-progress :percentage="dataStore.onUploadProgress" :format="format"    :stroke-width="5" v-show="dataStore.onUploadProgress" style="margin: 0;padding: 0" ></el-progress>
  <!-- 面包屑 -->
  <div class="bread-container">
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: `/` }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{path:`/home/material/materialInList`}" >材料进场列表</el-breadcrumb-item>
      <el-breadcrumb-item >材料进场修改页</el-breadcrumb-item>
    </el-breadcrumb>
  </div>

  <table class="mainTable">
    <tbody>
    <tr>
      <td style="background:#EFF6FF "><h3 style="color: #44a8da;background: #EFF6FF">修改材料进场信息表单</h3></td>
    </tr>
    <tr>
    </tr>
    <tr>
      <td style="background: #EFF6FF">
        <el-form
            :model="form"
            label-width="auto"
            style="max-width: 90%;padding-left: 8%;padding-top: 2%"
            :label-position="labelPosition"
            :size="size"
            ref="ruleFormRef"
            :rules="rules"
        >
          <!--          <el-form-item label="设备id">-->
          <!--            <el-input disabled v-model="form.id"/>-->
          <!--          </el-form-item>-->
          <el-form-item label="材料名称" prop="materialName">
            <el-input disabled v-model="form.materialName"/>
          </el-form-item>
          <el-form-item label="材料品牌" prop="brand">
            <el-input disabled v-model="form.brand"/>
          </el-form-item>
          <el-form-item label="材料型号" prop="model" >
            <el-input disabled v-model="form.model"/>
          </el-form-item>
          <!--          <el-form-item  label="材料编码">-->
          <!--            <el-input  disabled v-model="form.encode"/>-->
          <!--          </el-form-item>-->
          <el-form-item  label="原材料类型" prop="typeName" >
            <el-input  disabled v-model="newMaterialTypeName"/>
            <!--        <el-input  disabled v-model="form.typeName"/>-->
            <el-cascader
                placeholder="请选择新的材料类型"
                :options="materialTypeStore.fullMaterialType"
                filterable
                @change="getMaterialTypeName(form.typeName)"
                v-model="form.typeName"
                disabled
            />
          </el-form-item>
          <el-form-item label="材料数量单位" prop="pieces" >
            <el-input disabled v-model="form.pieces"/>
          </el-form-item>
          <el-form-item label="材料数量">
            <el-input @change="materialInNumberChange" v-model="form.number"/>
          </el-form-item>

          <el-form-item label="材料单价">
            <el-input @change="getTotalPrice"  v-model="price"/>
          </el-form-item>

          <el-form-item label="材料总价">
            <el-input disabled   v-model="totalPrice"/>
          </el-form-item>

          <el-form-item label="材料来源地">
            <el-select
                @change="handleParentChange"
                clearable
                filterable
                allow-create
                default-first-option
                :reserve-keyword="false"
                v-model="receiveFromProjectName"
                placeholder="请添加或者选择"
                size="large"
                style="margin: 0;padding: 0"
            >
              <el-option
                  v-for="item in receiveFromProjectList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
              />
            </el-select>
          </el-form-item>


          <el-form-item  label="材料进场描述" prop="description" >
            <el-input  v-model="form.description"/>
          </el-form-item>
        </el-form>
      </td>
    </tr>







    <tr>
      <td style="background:#EFF6FF "><h3>已     有     图     片</h3></td>
    </tr>
    <tr>
      <td>
        <div class="block" style="margin: 20px">
          <el-image v-for="(ele,index) in photoList" :key="index"
                    style="width: 150px; height: 100px"
                    :src="ele"
                    :zoom-rate="1.2"
                    :max-scale="5"
                    :min-scale="0.5"
                    :preview-src-list="getPreviewImgList(index)"
                    fit="cover"
                    @contextmenu.prevent
                    @contextmenu.stop="onContextMenu($event,index)"
          >
          </el-image>
        </div>
      </td>
    </tr>
    <tr>
      <td>
        <CameraCapture/>
      </td>
    </tr>
    <tr>
      <td>
        <FileUpload/>
      </td>
    </tr>
    <tr>
      <td colspan="2" style="background:#EFF6FF ">
        <el-button @click="modifyOneSummit(ruleFormRef)" type="primary" :disabled="disableSwitch" style="margin-top: 1%;margin-bottom: 1%" >确认修改</el-button>
      </td>
    </tr>
    </tbody>
  </table>
</template>

<style scoped lang="scss">
.mainTable {
  margin-left: 6%;
}

.bread-container {
  padding: 25px 10px;
  margin-left: 10px;
}
.divTable {
  position: absolute;
  top: 150px;
  bottom: 0;
  left: 300px;
  right: 0;
  margin: auto;
}


table, td,tr{
  border: 1px solid #44a8da;
  text-align: center;
  border-spacing: 0;
  border-collapse: collapse;
  height: 45px;
  width: 80%;
}

.tableTitle{

  border-right: 0 none;
  border-left: 0 none;
  text-align: center;
  font-size: large;
  font-weight: bold;
}

.demo-image__error .image-slot {
  font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}
.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}

img {
  width: 100px;
  height: 100px;
}

.demo-image .block {

  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  display: inline-block;
  width: 20%;
  box-sizing: border-box;
  vertical-align: top;
}
.demo-image .block:last-child {
  border-right: none;
}
.demo-image .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
.upload {
  width: 200px;
  height: 60px;
  top: 150px;
  bottom: 0;
  left: 300px;
  right: 0;
  margin: auto;
}
</style>